<?php 
	require_once("init.php"); 
?>

<?php
	$errorMessage = "";
	
	if (isset($_POST["submitForm"])) {
		// Update the date reported
		$qReportTopic = mysql_query("
			UPDATE topics
			SET 
				dateReported = now(), 
				points = points - 1
			WHERE topicId = '".$_POST["topicId"]."'
		");

		$userId = 1;
		if (isset($_SESSION["userId"])) {
			$userId = $_SESSION["userId"];
		}
		
		// Add user's moderation
		$qInsertModeration = mysql_query("
			INSERT INTO moderations (
				topicId,
				userId,
				sessionId,
				favor,
				dateModerated
			)
			VALUES (
				".$_POST["topicId"].",
				".$userId.",
				'".session_id()."',
				-1,
				now()
			)
		");
		
		// Update user points
		if (isset($_SESSION["userId"])) {
			$qUpdateUserPoints = mysql_query("
				UPDATE users
				SET 
					points = points + ".$moderateTopicPoints."
				WHERE 
					userId = ".$_SESSION["userId"]."
			");
		}
?>
<form id="reportSuccess" class="dialog" method="post" target="_self" action="redirect.php?url=index.php">
	<fieldset>
    <h1>Thank you!</h1>
    <p align="center">This topic has been reported.</p>
    <p align="center"><input class="submit" type="submit" name="submit" value="Continue" /></p>
  </fieldset>
</form>
<?php
	} else {
	
		$strCheckModeration = "
			SELECT moderationId
			FROM moderations
			WHERE topicId = ".$_GET["id"]."
		";
		if (isset($_SESSION["userId"])) {
			$strCheckModeration = $strCheckModeration."
				AND userId = ".$_SESSION["userId"]."
			";
		} else if (strlen(session_id()) > 0) {
			$strCheckModeration = $strCheckModeration."
				AND sessionId = '".session_id()."'
			";
		} else {
			$strCheckModeration = $strCheckModeration."
				AND 1 = 0
			";
		}
		$qCheckModeration = mysql_query($strCheckModeration);
		
		// if vote is already made, display error message
		if (mysql_num_rows($qCheckModeration) > 0) {
?>

<div id="report-fail" title="Oops!" class="panel">
	<p>You have previously reported or moderated this topic.</p>
</div>

<?php
		} else {
?>

<form id="reportForm" class="dialog" method="post" action="reporttopic.php">
	<input type="hidden" name="submitForm" value="submitForm" />
	<input type="hidden" name="topicId" value="<?php print $_GET["id"]; ?>" />
	<fieldset>
    <h1>Report this topic?</h1>
    <a class="button leftButton" type="cancel">Cancel</a>
    <a class="button blueButton" type="submit">Yes</a>
  </fieldset>
</form>

<?php
		}
	}
?>